<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { ClusterConfigClient, ClusterConfigSummaryViewModel, RouteConfig, RouteConfigClient } from '../../services/client';
import { FormInstance, FormRules } from 'element-plus';
import Errors from '../../types/Errors';
import TimeSpanSelect from '../../components/basic/TimeSpanSelect.vue';
import NtmMetaDataEditor from '../../components/Editors/NtmMetaDataEditor.vue';
import MenuItemBox from '../../components/basic/MenuItemBox.vue';
import NtmRouteMatchEditor from '../../components/Editors/NtmRouteMatchEditor.vue'
import { useClient } from '../../constants/client';

const clusterConfigClient = useClient(ClusterConfigClient)

const emits = defineEmits({
    save(_value: RouteConfig) {
        return true;
    },
    cancel() {
        return true
    }
})

const props = defineProps<{ data: RouteConfig, isCreate?: boolean }>();

const allNames = ['basic', 'cluster', 'match', 'policies', 'transforms', 'metadata']
const activeNames = ref<string[]>(allNames);
const clusters = ref<ClusterConfigSummaryViewModel[]>([]);
const loadingClusters = ref(false)

const loadClusterByClusterId = (query: string) => {
    loadingClusters.value = true;
    clusterConfigClient.findById(query)
        .then(datas => {
            clusters.value = datas;
        })
        .catch(err => {
            console.log('RouteConfigEditor/ClusterSelect:load failed', err)
        })
        .finally(() => {
            loadingClusters.value = false;
        })
}

const { isCreate = false } = props;
let config = reactive(props.data)

const formRef = ref<FormInstance>()
const errors = ref<Errors>({})

const disableMetaData = computed(() => {
    return config.metadata === undefined
})
const initMetaData = () => {
    config.metadata = {}
}
const removeMetaData = () => {
    config.metadata = undefined
}

const disableTransforms = computed(() => {
    return config.transforms === undefined
})
const initTransforms = () => {
    config.transforms = []
}
const removeTransforms = () => {
    config.transforms = undefined
}

const rules = reactive<FormRules<RouteConfig>>({
    routeId: [
        { required: true, trigger: 'change', message: '请输入Route Id' }
    ],
    metadata: [
        {
            validator: (_rule, _value, callback, _source, _options) => {
                const errorkeys = Object.keys(errors.value);
                if (errorkeys.length > 0) {
                    const errorMessage = errorkeys.map(key => {
                        return `键：${key}: ${errors.value[key].join(',')}`
                    }).join(';');
                    callback(errorMessage)
                }
                else {
                    callback();
                }
            },
            trigger: ['change', 'blur']
        }
    ],
})

const expendAll = () => {
    activeNames.value = allNames;
}

const save = () => {
    formRef.value?.validate(isValid => {
        if (isValid) {
            emits('save', config)
        }
    })
}

const cancel = () => {
    emits('cancel')
}
</script>

<template>
    <ElContainer style="height: 100%;">
        <ElAside>
            <ElScrollbar>
                <ElMenu default-active="basic">
                    <ElMenuItem index="basic">
                        <ElText>
                            基础设置
                            <ElIcon>
                                <Check />
                            </ElIcon>
                        </ElText>
                    </ElMenuItem>
                    <ElMenuItem index="cluster">
                        <ElText>
                            集群
                            <ElIcon>
                                <Check />
                            </ElIcon>
                        </ElText>
                    </ElMenuItem>
                    <ElMenuItem index="match">
                        <ElText>
                            匹配
                            <ElIcon>
                                <Check />
                            </ElIcon>
                        </ElText>
                    </ElMenuItem>
                    <ElMenuItem index="policies">
                        <ElText>
                            策略
                            <ElIcon>
                                <Check />
                            </ElIcon>
                        </ElText>
                    </ElMenuItem>
                    <ElMenuItem index="transforms">
                        <template #title>
                            <MenuItemBox>
                                <template #default>
                                    <ElText truncated>
                                        Transforms
                                        <ElIcon v-if="!disableTransforms">
                                            <Check />
                                        </ElIcon>
                                    </ElText>
                                </template>
                                <template #right>
                                    <ElButton v-if="disableTransforms" @click="initTransforms" size="small">
                                        添加
                                    </ElButton>
                                    <ElButton v-else type="danger" @click="removeTransforms" size="small">
                                        移除
                                    </ElButton>
                                </template>
                            </MenuItemBox>
                        </template>
                    </ElMenuItem>
                    <ElMenuItem index="metadata">
                        <template #title>
                            <MenuItemBox>
                                <template #default>
                                    <ElText truncated>
                                        元数据
                                        <ElIcon v-if="!disableMetaData">
                                            <Check />
                                        </ElIcon>
                                    </ElText>
                                </template>
                                <template #right>
                                    <ElButton v-if="disableMetaData" @click="initMetaData" size="small">
                                        添加
                                    </ElButton>
                                    <ElButton v-else type="danger" @click="removeMetaData" size="small">
                                        移除
                                    </ElButton>
                                </template>
                            </MenuItemBox>
                        </template>
                    </ElMenuItem>
                </ElMenu>
            </ElScrollbar>
        </ElAside>
        <ElContainer class="route-editor-main">
            <ElHeader>
                <ElButton size="small" @click="expendAll()">全部展开</ElButton>
                <ElButton size="small" @click="activeNames = []">全部折叠</ElButton>
            </ElHeader>

            <ElScrollbar>
                <ElRow>
                    <ElCol :span="24">
                        <ElForm ref="formRef" :rules="rules" :model="config" label-width="230px" label-position="top"
                            status-icon>
                            <ElCollapse v-model="activeNames">
                                <ElCollapseItem name="basic">
                                    <template #title>
                                        <h1>基础设置</h1>
                                    </template>
                                    <ElFormItem prop="routeId" label="Route Id">
                                        <ElInput :disabled="!isCreate" v-model="config.routeId"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="order" label="Order">
                                        <ElInputNumber v-model="config.order"></ElInputNumber>
                                    </ElFormItem>
                                </ElCollapseItem>
                                <ElCollapseItem name="cluster">
                                    <template #title>
                                        <h1>集群</h1>
                                    </template>
                                    <ElFormItem name="clusterId">
                                        <ElSelect v-model="config.clusterId" clearable filterable :loading="loadingClusters"
                                            :remote-method="loadClusterByClusterId" remote placeholder="输入Cluster Id查找" default-first-option>
                                            <ElOption v-for="(cluster) in clusters" :key="cluster.clusterId"
                                                :label="cluster.clusterId" :value="cluster.clusterId">

                                            </ElOption>
                                        </ElSelect>
                                    </ElFormItem>
                                </ElCollapseItem>
                                <ElCollapseItem name="match">
                                    <template #title>
                                        <h1>匹配</h1>
                                    </template>
                                    <NtmRouteMatchEditor v-model="config.match"></NtmRouteMatchEditor>
                                </ElCollapseItem>
                                <ElCollapseItem name="policies">
                                    <template #title>
                                        <h1>策略</h1>
                                    </template>
                                    <ElFormItem prop="authorizationPolicy" label="Authorization Policy">
                                        <ElInput v-model="config.authorizationPolicy"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="rateLimiterPolicy" label="RateLimter Policy">
                                        <ElInput v-model="config.rateLimiterPolicy"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="outputCachePolicy" label="Output Cache Policy">
                                        <ElInput v-model="config.outputCachePolicy"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="timeoutPolicy" label="Timeout Policy">
                                        <ElInput v-model="config.timeoutPolicy"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="timeout" label="Timeout">
                                        <TimeSpanSelect v-model="config.timeout"></TimeSpanSelect>
                                    </ElFormItem>
                                    <ElFormItem prop="corsPolicy" label="Cors Policy">
                                        <ElInput v-model="config.corsPolicy"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="maxRequestBodySize" label="Max Request Body Size">
                                        <ElInputNumber v-model="config.maxRequestBodySize"></ElInputNumber>
                                    </ElFormItem>
                                </ElCollapseItem>
                                <ElCollapseItem name="transforms" v-if="!disableTransforms">
                                    <template #title>
                                        <h1>转换</h1>
                                    </template>
                                    <ElFormItem prop="transforms">
                                        <NtmTransformsEditor v-model="config.transforms"></NtmTransformsEditor>
                                        <a
                                            href="https://microsoft.github.io/reverse-proxy/articles/transforms.html">help!</a>
                                    </ElFormItem>
                                </ElCollapseItem>
                                <ElCollapseItem name="metadata" v-if="!disableMetaData">
                                    <template #title>
                                        <h1>元数据</h1>
                                    </template>
                                    <ElFormItem prop="metadata" label="Metadata">
                                        <NtmMetaDataEditor v-model="config.metadata"></NtmMetaDataEditor>
                                    </ElFormItem>
                                </ElCollapseItem>
                            </ElCollapse>
                        </ElForm>
                    </ElCol>
                </ElRow>
            </ElScrollbar>

            <ElFooter>
                <ElRow style="margin-top: 10px;">
                    <ElCol>
                        <ElButton type="primary" @click="save">保存</ElButton>
                        <ElButton @click="cancel">取消</ElButton>
                    </ElCol>
                </ElRow>
            </ElFooter>
        </ElContainer>
    </ElContainer>
</template>

<style scoped>
.el-form {
    padding-left: 12px;
}

h1 {
    font-size: 24px;
}

.cluster-editor-main {
    border-left: solid 1px var(--el-menu-border-color);
}

:global(.el-form-item__label) {
    font-weight: 600;
}
</style>